"use strict";
import axios from "axios";
import store from "../store";
// create an axios instance

const request = axios.create({
  //baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
	//baseURL: "./", 
	baseURL: "http://127.0.0.1:8083/", 
  timeout: 60000 // request timeout
});
// request interceptor
request.interceptors.request.use(
  config => {
    // Do something before request is sent
	
    console.info("请求拦截");
	let activeUser = store.getters.getActiveUser();
	if(activeUser !=null){
		 config.headers["userName"] = store.getters.getActiveUser().userName;
		  config.headers["accessToken"] = store.getters.getActiveUser().accessToken;
	}
    return config;
  },
  error => {
    //message.error(error.message)
    return Promise.reject(error);
  }
);

// response interceptor
request.interceptors.response.use(
  response => {
    if (response.data.code == "4001") {
		return  Promise.reject(response);
		//token失效,刷新token
		//跳转到登录页面
		/* store.dispatch("tokenRefresh",store.getters.getActiveUser()).then(() => {
			let config = response.config;
			let activeUser = store.getters.getActiveUser();
			if(activeUser !=null){
				 config.headers["userName"] = store.getters.getActiveUser().userName;
				  config.headers["accessToken"] = store.getters.getActiveUser().accessToken;
			}
			return  Promise.resolve(axios(config));
		});	 */	
    }else{
		return response;
	}
    
  },
  error => {
	  
	  return Promise.reject(error);
  }
);



request.interceptors.response.use(
  response => {
	return response;
    
  },
  error => {
	  let response = error;
	 // console.info(error)
	  try{
		  return  new Promise((resolve,reject)=>{
			  store.dispatch("tokenRefresh",store.getters.getActiveUser()).then(() => {
				  
				  
			  	let config = response.config;
			  	let activeUser = store.getters.getActiveUser();
			  	if(activeUser !=null){
			  		 config.headers["userName"] = store.getters.getActiveUser().userName;
			  		  config.headers["accessToken"] = store.getters.getActiveUser().accessToken;
			  	}
			  	return resolve(axios(config));
			  }).catch(err=>{
				  store.dispatch('LogOut').then(()=>{
				     location.reload()
				      //this.$router.push({path:'/login'})
				  });
			  });
		  });
	
		  }catch(e){
		  	 return Promise.reject(error);
		  }
  }
);

export default request;
